<!DOCTYPE html>
<html lang="zh-CN">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="icon" href="favicon.ico" type="image/x-icon">
        <title>GPT提问</title>
        <script src="./resource/marked.min.js"></script>
        <script src="./resource/highlight.min.js"></script>
        <link href="./resource/css2.css" rel="stylesheet">
        <link href="./resource/github.min.css" rel="stylesheet">
        <style>
            /* 重置样式 */
            * {
                box-sizing: border-box;
            }

            body {
                font-family: 'Inter', sans-serif;
                background: linear-gradient(135deg, #f0f4f8, #d1d9e6);
                /* 浅蓝色渐变背景 */
                color: #333;
                /* 深色文字 */
                line-height: 1.6;
                height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 20px;
                margin: 0;
            }

            h1 {
                text-align: center;
                color: #2c3e50;
                /* 深蓝色标题 */
                margin-top: 10px;
                font-size: 1.5rem;
                font-weight: 700;
            }

            .container {
                width: 100%;
                max-width: 1600px;
                height: 100%;
                background-color: #ffffff;
                /* 容器背景 */
                border-radius: 12px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
                overflow: hidden;
                display: flex;
                flex-direction: column;
            }

            .editor {
                display: flex;
                flex-direction: column;
                flex: 1;
                gap: 20px;
                padding: 20px;
                height: calc(100% - 80px);
                /* 减去标题高度 */
            }

            textarea {
                width: 100%;
                height: 100px;
                padding: 20px;
                font-family: 'JetBrains Mono', monospace;
                font-size: 16px;
                border: 2px solid #e0e0e0;
                /* 输入框边框 */
                border-radius: 8px;
                resize: none;
                outline: none;
                background-color: #ffffff;
                /* 输入框背景 */
                color: #333;
                /* 输入框文字 */
                transition: border-color 0.3s ease;
            }

            textarea:focus {
                border-color: #3498db;
                /* 聚焦时的边框颜色 */
            }

            textarea::-webkit-scrollbar {
                width: 0.5rem;
            }

            textarea::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 0.5rem;
            }

            textarea::-webkit-scrollbar-thumb {
                background: #3498db;
                border-radius: 0.5rem;
            }

            textarea::-webkit-scrollbar-thumb:hover {
                background: #2980b9;
            }

            #preview {
                width: 100%;
                flex: 1;
                padding: 20px;
                border: 2px solid #e0e0e0;
                /* 预览区域边框 */
                border-radius: 8px;
                overflow-y: auto;
                background-color: transparent;
                /* 预览区域背景 */
                color: #333;
                /* 预览区域文字 */
            }

            #preview::-webkit-scrollbar {
                width: 0.5rem;
            }

            #preview::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 0.5rem;
            }

            #preview::-webkit-scrollbar-thumb {
                background: #3498db;
                border-radius: 0.5rem;
            }

            #preview::-webkit-scrollbar-thumb:hover {
                background: #2980b9;
            }

            /* 重置样式 */
            #preview * {
                box-sizing: border-box;
            }

            #preview h1, h2, h3 {
                margin-top: 1.5rem !important;
                margin-bottom: 1rem !important;
                color: #2c3e50;
            }

            #preview h1 {
                font-size: 2rem;
                border-bottom: 2px solid #e0e0e0;
                padding-bottom: 0.5rem;
            }

            #preview h2 {
                font-size: 1.75rem;
            }

            #preview h3 {
                font-size: 1.5rem;
            }

            #preview p {
                margin-bottom: 1rem;
                line-height: 1.8;
            }

            #preview a {
                color: #3498db;
                text-decoration: none;
                font-weight: 500;
            }

            #preview a:hover {
                text-decoration: underline;
            }

            #preview ul, ol {
                margin-bottom: 1rem;
                padding-left: 1.5rem;
            }

            #preview ul {
                list-style-type: disc;
                margin-top: 10px;
            }

            #preview ol {
                list-style-type: decimal;
                margin-left: 1rem;
            }

            #preview li {
                margin-bottom: 0.5rem;
            }

            #preview code {
                font-family: 'JetBrains Mono', monospace;
                background-color: #f5f7ff;
                padding: 2px 6px;
                border-radius: 4px;
                color: #2c3e50;
                font-size: 14px;
            }

            #preview pre {
                background-color: #f5f7ff;
                padding: 15px;
                border-radius: 6px;
                margin: 1rem 0;
                font-size: 14px;
                line-height: 1.5;
                overflow: auto;
            }

            #preview pre::-webkit-scrollbar {
                width: 0.5rem;
                height: 0.5rem;
            }

            #preview pre::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 0.5rem;
            }

            #preview pre::-webkit-scrollbar-thumb {
                background: #3498db;
                border-radius: 0.5rem;
            }

            #preview pre::-webkit-scrollbar-thumb:hover {
                background: #2980b9;
            }

            #preview pre code {
                background-color: transparent;
                padding: 0;
                color: #2c3e50;
                width: fit-content;
            }

            #preview pre code .copy-button {
                position: absolute;
                right: 10px;
                top: 10px;
                background-color: #3498db;
                color: white;
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.3s;
            }

            #preview pre code .copy-button:hover {
                background-color: #2980b9;
            }

            #preview pre code .preview-button {
                position: absolute;
                right: 80px;
                top: 10px;
                background-color: #3498db;
                color: white;
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.3s;
            }

            #preview pre code .preview-button:hover {
                background-color: #2980b9;
            }

            #preview blockquote {
                border-left: 4px solid #3498db;
                color: #555;
                margin: 1rem 0;
                font-style: italic;
                background-color: #f0f4f8;
                padding: 10px;
                border-radius: 4px;
            }

            #preview table {
                border-spacing: 0;
                border-collapse: collapse;
            }

            #preview table tr {
                border-top: 1px solid #c6cbd1;
            }

            #preview table tr td, table tr th {
                padding: 6px 13px !important;
                border: 1px solid #dfe2e5;
            }

            #preview hr {
                margin: 20px !important;
            }

            /* 审查按钮样式 */
            #review-btn, #export-btn, #export-markdown-btn, #copy-reply-btn, #change-input-btn, #config-sk-btn, #config-attach-btn, #view-util-code-btn, #history-btn, #export-history-btn, #attach-btn {
                background-color: #3498db;
                color: white;
                border: none;
                padding: 0.5rem 1rem;
                border-radius: 4px;
                cursor: pointer;
                font-size: 1rem;
                transition: background-color 0.3s;
            }

            #review-btn:hover, #export-btn:hover, #export-markdown-btn:hover, #copy-reply-btn:hover, #change-input-btn:hover, #config-sk-btn:hover, #config-attach-btn:hover, #view-util-code-btn:hover, #history-btn:hover, #export-history-btn:hover, #attach-btn:hover {
                background-color: #2980b9;
                /* 深一点的蓝色 */
            }

            /* 模态对话框样式 */
            .modal {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                justify-content: center;
                align-items: center;
            }

            .modal-content {
                background-color: white;
                padding: 2rem;
                border-radius: 8px;
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
                width: 500px;
                max-width: 90%;
                text-align: center;
            }

            .modal-content input {
                width: 100%;
                padding: 0.5rem;
                margin: 1rem 0;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 1rem;
                outline: none;
            }

            .modal-content input:focus {
                border: 1px solid #3498db;
            }

            .modal-content button {
                background-color: #3498db;
                color: white;
                border: none;
                padding: 0.5rem 1rem;
                border-radius: 4px;
                cursor: pointer;
                font-size: 1rem;
                margin: 0 0.5rem;
            }

            .modal-content button:hover {
                background-color: #2980b9;
            }

            #history-list {
                padding: 15px 10px 15px 0;
                width: 100%;
                height: fit-content;
                max-height: 500px;
                overflow-y: auto;
            }

            #history-list::-webkit-scrollbar {
                width: 0.5rem;
            }

            #history-list::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 0.5rem;
            }

            #history-list::-webkit-scrollbar-thumb {
                background: #3498db;
                border-radius: 0.5rem;
            }

            #history-list::-webkit-scrollbar-thumb:hover {
                background: #2980b9;
            }

            #history-list p {
                white-space: nowrap;
                word-break: break-all;
                text-overflow: ellipsis;
                overflow: hidden;
                margin-bottom: 15px;
                border: 1px solid #ccc;
                padding: 15px;
                cursor: pointer;
            }

            #history-list p.active {
                border: 1px solid #3498db;
            }

            .select-container {
                padding-top: 15px;
                display: flex;
                justify-content: center;
            }

            .select-container button {
                background-color: #28a745;
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                cursor: pointer;
                transition: background-color 0.3s;
                outline: none;
                border: none;
            }

            .select-container button:hover {
                background-color: #218838;
            }

            .attach-container {
                margin-bottom: 1rem;
                margin-top: 1rem;
                width: 100%;
                height: fit-content;
                max-height: 500px;
                overflow-y: auto;
            }

            .attach-container::-webkit-scrollbar {
                width: 0.5rem;
            }

            .attach-container::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 0.5rem;
            }

            .attach-container::-webkit-scrollbar-thumb {
                background: #3498db;
                border-radius: 0.5rem;
            }

            .attach-container::-webkit-scrollbar-thumb:hover {
                background: #2980b9;
            }

            .attach-container .custom-file-input, .attach-container .custom-dir-input {
                display: none;
            }

            .attach-container ul {
                list-style-type: none;
            }

            .attach-container li {
                background-color: #d4edda;
                margin: 10px 0;
                padding: 10px;
                border-radius: 5px;
                cursor: pointer;
                transition: background-color 0.3s;
                word-break: break-all;
            }

            .attach-container li:hover {
                background-color: #c3e6cb;
            }

            #file-content-modal .modal-content {
                width: 1200px;
                padding-bottom: 1rem;
                max-height: 80%;
                display: flex;
                flex-direction: column;
            }

            #file-content-modal .modal-content .code {
                background-color: #f5f7ff;
                padding: 15px;
                border-radius: 6px;
                margin: 1rem 0;
                overflow: auto;
                flex: 1;
            }

            #file-content-modal .modal-content pre {
                font-family: 'JetBrains Mono', monospace;
                background-color: #f5f7ff;
                color: #2c3e50;
                font-size: 16px;
                border-radius: 6px;
                line-height: 1.5;
                text-align: left;
                height: fit-content;
            }

            #file-content-modal .modal-content .code::-webkit-scrollbar {
                width: 0.5rem;
                height: 0.5rem;
            }

            #file-content-modal .modal-content .code::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 0.5rem;
            }

            #file-content-modal .modal-content .code::-webkit-scrollbar-thumb {
                background: #3498db;
                border-radius: 0.5rem;
            }

            #file-content-modal .modal-content .code::-webkit-scrollbar-thumb:hover {
                background: #2980b9;
            }

            #file-list li:first-child {
                margin-top: 0;
            }

            #file-list li:last-child {
                margin-bottom: 0;
            }

            .modal-content .code .copy-button {
                position: absolute;
                right: 10px;
                top: 10px;
                background-color: #3498db;
                color: white;
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.3s;
            }

            .modal-content .code .copy-button:hover {
                background-color: #2980b9;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <div style="position: relative; display: flex; height: 60px">
                <h1 style="flex: 1"></h1>
                <div style="width: fit-content; gap: 10px; height: 100%; align-items: center; display: flex; padding-right: 20px">
                    <button id="history-btn">历史记录</button>
                    <button id="export-history-btn">导出历史记录</button>
                    <button id="change-input-btn">全屏输入</button>
                    <button id="config-sk-btn">配置SK</button>
                    <button id="config-attach-btn">配置附件</button>
                    <button id="view-util-code-btn">查看工具类</button>
                    <button id="export-btn">导出回答</button>
                    <button id="export-markdown-btn">导出Markdown回答</button>
                    <button id="copy-reply-btn">复制回答</button>
                    <button id="attach-btn">上传附件</button>
                    <button id="review-btn">提问</button>
                </div>
            </div>
            <div class="editor">
                <textarea id="codeInput" placeholder="请输入问题..."></textarea>
                <div id="preview">
                    回答结果将显示在这里...
                </div>
            </div>
        </div>

        <div id="sk-modal" class="modal">
            <div class="modal-content">
                <h2>配置SK</h2>
                <input type="text" id="sk-input" placeholder="请输入SK">
                <div>
                    <button id="save-sk-btn">保存</button>
                    <button id="cancel-sk-btn">取消</button>
                </div>
            </div>
        </div>

        <div id="history-modal" class="modal">
            <div class="modal-content">
                <h2>历史记录</h2>
                <div id="history-list"></div>
                <div>
                    <button id="change-history-btn">确认</button>
                    <button id="cancel-history-btn">取消</button>
                </div>
            </div>
        </div>

        <div id="attach-modal" class="modal">
            <div class="modal-content">
                <h2>附件上传</h2>
                <div class="select-container">
                    <button id="select-file">选择文件</button>
                    <button id="select-dir">选择文件夹</button>
                    <button id="clear-select">清空列表</button>
                </div>
                <div class="attach-container">
                    <input type="file" id="import-file" class="custom-file-input" multiple />
                    <input type="file" id="import-dir" class="custom-dir-input" webkitdirectory />
                    <ul id="file-list" style="margin: 0; padding: 0 0.5rem 0 0;"></ul>
                </div>
                <div>
                    <button id="save-attach-btn">确认</button>
                    <button id="cancel-attach-btn">取消</button>
                </div>
            </div>
        </div>

        <div id="file-content-modal" class="modal">
            <div class="modal-content">
                <h2>文件内容</h2>
                <div class="code" style="position: relative">
                    <pre></pre>
                    <button class="copy-button" onclick="copyContent(this)">复制</button>
                </div>
            </div>
        </div>

        <div id="config-attach-modal" class="modal">
            <div class="modal-content" style="width: 600px;">
                <h2>配置附件规则</h2>
                <p><strong>允许的文件扩展名（每行一个，带点）：</strong></p>
                <textarea id="allowed-extensions-input" rows="8" style="width: 100%; font-family: 'JetBrains Mono', monospace; font-size: 16px"></textarea>

                <p><strong>要排除的文件夹名称（每行一个）：</strong></p>
                <textarea id="excluded-folders-input" rows="6" style="width: 100%; font-family: 'JetBrains Mono', monospace; font-size: 16px"></textarea>

                <div style="margin-top: 1rem; text-align: right;">
                    <button id="save-config-attach-btn">保存</button>
                    <button id="cancel-config-attach-btn">取消</button>
                </div>
            </div>
        </div>

        <script>
            function copyContent(elem) {
                const codeContent = elem.parentElement.children[0].innerText;
                navigator.clipboard.writeText(codeContent).then(() => {
                    elem.textContent = '已复制';
                    setTimeout(() => {
                        elem.textContent = '复制';
                    }, 3000); // 3秒后恢复
                }).catch(() => {
                    alert('复制失败，请手动复制！');
                });
            }
        </script>

        <script>
            // 获取DOM元素
            const codeInput = document.getElementById('codeInput');
            const reviewButton = document.getElementById('review-btn');
            const preview = document.getElementById('preview');

            const changeInputBtn = document.getElementById('change-input-btn');
            changeInputBtn.addEventListener('click', () => {
                changeInputDisplay();
            });

            function changeInputDisplay() {
                if (changeInputBtn.textContent === "全屏输入") {
                    changeInputBtn.textContent = "取消全屏";
                    codeInput.style.height = "100%";
                    preview.style.display = "none";
                } else {
                    changeInputBtn.textContent = "全屏输入";
                    codeInput.style.height = "100px";
                    preview.style.display = "block";
                }
            }

            // 绑定审查按钮点击事件
            reviewButton.addEventListener('click', async () => {
                const savedSk = localStorage.getItem('sk');
                if (!savedSk) {
                    alert('请先配置SK！');
                    return;
                }

                const code = codeInput.value;
                if (!code) {
                    alert("请输入问题后提问！");
                    return;
                }

                if (isAnswering) {
                    alert("当前正在回答中！");
                    return;
                }

                if (changeInputBtn.textContent === "取消全屏") {
                    changeInputDisplay();
                }

                preview.textContent = "";
                if (attachContent) {
                    const text = code + "\n附件内容如下：\n" + attachContent;
                    callGpt(text);
                } else {
                    callGpt(code);
                }
            });

            const exportBtn = document.getElementById('export-btn');
            exportBtn.addEventListener('click', () => {
                if (isAnswering) {
                    alert("当前正在回答中！");
                    return;
                }
                downloadHTMLFile();
            });

            const exportMarkdownBtn = document.getElementById('export-markdown-btn');
            exportMarkdownBtn.addEventListener('click', () => {
                if (isAnswering) {
                    alert("当前正在回答中！");
                    return;
                }
                downloadMarkdownFile();
            });

            function downloadMarkdownFile() {
                const blob = new Blob([replyContent], {type: 'text/markdown'});
                const url = URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = 'export-note.md';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }

            const copyReplyBtn = document.getElementById('copy-reply-btn');
            copyReplyBtn.addEventListener('click', () => {
                if (isAnswering) {
                    alert("当前正在回答中！");
                    return;
                }
                navigator.clipboard.writeText(replyContent).then(() => {
                    alert('复制成功！');
                }).catch(() => {
                    alert('复制失败，请手动复制！');
                });
            });

            // 触发文件下载
            function downloadHTMLFile() {
                const htmlContent = generateHTMLFile();
                const blob = new Blob([htmlContent], {type: 'text/html'});
                const url = URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = 'export-note.html';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }

            // 配置SK的功能
            const configSkBtn = document.getElementById('config-sk-btn');
            const skModal = document.getElementById('sk-modal');
            const skInput = document.getElementById('sk-input');
            const saveSkBtn = document.getElementById('save-sk-btn');
            const cancelSkBtn = document.getElementById('cancel-sk-btn');

            // 打开模态对话框
            configSkBtn.addEventListener('click', () => {
                skModal.style.display = 'flex';
                skInput.value = localStorage.getItem("sk");
                skInput.focus();
            });

            // 保存SK
            saveSkBtn.addEventListener('click', () => {
                const sk = skInput.value.trim();
                if (sk) {
                    localStorage.setItem('sk', sk);
                    alert('SK已保存！');
                    skModal.style.display = 'none';
                    skInput.value = ''; // 清空输入框
                } else {
                    alert('SK不能为空！');
                }
            });

            // 取消配置
            cancelSkBtn.addEventListener('click', () => {
                skModal.style.display = 'none';
                skInput.value = ''; // 清空输入框
            });

            const exportHistoryBtn = document.getElementById('export-history-btn');
            exportHistoryBtn.addEventListener('click', () => {
                if (isAnswering) {
                    alert("当前正在回答中！");
                    return;
                }
                exportHistoryList();
            });

            function exportHistoryList() {
                const blob = new Blob([JSON.stringify(historyList)], {type: 'text/json'});
                const url = URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = 'export-history-list.json';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }

            const attachBtn = document.getElementById('attach-btn');
            const attachModal = document.getElementById('attach-modal');
            const saveAttachBtn = document.getElementById('save-attach-btn');
            const cancelAttachBtn = document.getElementById('cancel-attach-btn');
            const importFileInput = document.getElementById('import-file');
            const importDirInput = document.getElementById('import-dir');
            const fileListElem = document.getElementById('file-list');
            const fileList = [];
            const selectFileElem = document.getElementById("select-file");
            const selectDirElem = document.getElementById("select-dir");
            const clearSelectElem = document.getElementById("clear-select");
            let attachContent = "";

            selectFileElem.addEventListener('click', () => {
                importFileInput.click();
            });

            selectDirElem.addEventListener('click', () => {
                importDirInput.click();
            });

            clearSelectElem.addEventListener('click', () => {
                if (confirm("确定清空列表吗")) {
                    importFileInput.value = null;
                    importDirInput.value = null;
                    fileList.length = 0;
                    updateFileList();
                }
            });

            document.getElementById("view-util-code-btn").onclick = function () {
                showCodeContent();
            };

            async function showCodeContent() {
                fileContentModal.style.display = 'flex';
                fileContentH2.innerHTML = "collect-files.js";

                fileContentPre.innerText = `const fs = require('fs');
const path = require('path');
const readline = require('readline');

// ================== 交互式输入接口 ==================
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// ================== 配置区域（可自定义）==================
const OUTPUT_FILE = 'context_output.txt';   // 输出文件名

// 默认忽略的目录（隐藏目录或构建产物等）
const IGNORE_DIRS = [
  '.git', '.svn', '.idea', '__pycache__',
  'node_modules', 'dist', 'build', 'out',
  '.next', '.nuxt', '.output', 'coverage',
  '.DS_Store', 'tmp', 'temp'
];

// 默认允许的文件扩展名（已包含前端、后端、配置、文档等常用类型）
const ALLOWED_EXTENSIONS = [
  '.js', '.jsx', '.ts', '.tsx',
  '.html', '.css', '.scss', '.less',
  '.json', '.xml', '.yml', '.yaml', '.toml',
  '.md', '.markdown', '.txt',
  '.py', '.java', '.cpp', '.c', '.h', '.hpp',
  '.sh', '.bash', '.zsh', '.ps1',
  '.csv', '.properties', '.env',
  '.vue', '.go', '.rs', '.php', '.rb', '.swift',
  '.log' // 可选：日志文件，视情况决定是否保留
];

// =============================================

function shouldProcessFile(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  return ALLOWED_EXTENSIONS.includes(ext);
}

function shouldIgnoreDir(dirName) {
  return IGNORE_DIRS.includes(dirName);
}

function walkDir(dir, relativePath = '') {
  const entries = fs.readdirSync(dir, { withFileTypes: true });
  let filesContent = '';

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    const relPath = path.join(relativePath, entry.name);

    if (entry.isDirectory()) {
      if (!shouldIgnoreDir(entry.name)) {
        filesContent += walkDir(fullPath, relPath);
      }
    } else if (entry.isFile()) {
      if (shouldProcessFile(fullPath)) {
        try {
          const content = fs.readFileSync(fullPath, 'utf8');
          filesContent += \`=== File: \${relPath} ===\\n\`;
          filesContent += content;
          filesContent += \`\\n\\n\`; // 添加空行分隔
        } catch (err) {
          console.warn(\`无法读取文件: \${fullPath}\`, err.message);
        }
      }
    }
  }

  return filesContent;
}

// 主函数 - 使用异步方式等待用户输入
async function main() {
  const rootDir = await new Promise((resolve) => {
    rl.question('请输入要遍历的目录路径（例如 ./src 或 ../my-project）: ', (input) => {
      rl.close();
      resolve(input.trim());
    });
  });

  // 处理相对路径
  const resolvedDir = path.resolve(rootDir);

  if (!fs.existsSync(resolvedDir)) {
    console.error(\`❌ 错误：目录不存在 - \${rootDir}\`);
    process.exit(1);
  }

  if (!fs.statSync(resolvedDir).isDirectory()) {
    console.error(\`❌ 错误：指定的路径不是一个目录 - \${rootDir}\`);
    process.exit(1);
  }

  console.log(\`✅ 开始遍历目录: \${resolvedDir}\`);
  const output = walkDir(resolvedDir);

  fs.writeFileSync(OUTPUT_FILE, output, 'utf8');
  console.log(\`✅ 文件内容已写入: \${path.resolve(OUTPUT_FILE)}\`);
}

main();`;
            }

            const fileContentModal = document.getElementById('file-content-modal');
            const fileContentH2 = document.getElementById('file-content-modal').getElementsByTagName("h2")[0];
            const fileContentPre = document.getElementById('file-content-modal').getElementsByTagName("pre")[0];
            let currentFile = null;

            window.onclick = event => {
                if (event.target === fileContentModal) {
                    fileContentModal.style.display = 'none';
                }
            };

            function updateFileList() {
                fileListElem.innerHTML = '';
                fileList.forEach(file => {
                    const li = document.createElement('li');
                    li.textContent = file.title;
                    li.onclick = function () {
                        fileContentModal.style.display = 'flex';
                        fileContentH2.innerHTML = file.title + " 文件内容";
                        fileContentPre.innerText = file.content;
                        currentFile = file;
                    }
                    fileListElem.appendChild(li);
                });
            }

            // 默认配置
            const DEFAULT_CONFIG = {
                allowedExtensions: [
                    '.js', '.jsx', '.ts', '.tsx',
                    '.html', '.css', '.scss', '.less',
                    '.json', '.xml', '.yml', '.yaml',
                    '.md', '.markdown',
                    '.txt', '.log',
                    '.py', '.java', '.cpp', '.c', '.h', '.hpp',
                    '.sh', '.bash', '.zsh',
                    '.csv', '.properties', '.vue'
                ],
                excludeFolders: ['node_modules', '.git', '.svn', '.idea', '__pycache__', '.DS_Store']
            };

            // 获取当前配置
            function getAttachConfig() {
                const saved = localStorage.getItem('attachConfig');
                if (saved) {
                    return JSON.parse(saved);
                } else {
                    // 初始保存默认值
                    const config = { ...DEFAULT_CONFIG };
                    localStorage.setItem('attachConfig', JSON.stringify(config));
                    return config;
                }
            }

            // 加载配置到输入框
            function loadAttachConfigToModal() {
                const config = getAttachConfig();
                document.getElementById('allowed-extensions-input').value = config.allowedExtensions.join('\n');
                document.getElementById('excluded-folders-input').value = config.excludeFolders.join('\n');
            }

            const configAttachBtn = document.getElementById('config-attach-btn');
            const configAttachModal = document.getElementById('config-attach-modal');
            const saveConfigAttachBtn = document.getElementById('save-config-attach-btn');
            const cancelConfigAttachBtn = document.getElementById('cancel-config-attach-btn');

            // 打开配置模态框
            configAttachBtn.addEventListener('click', () => {
                loadAttachConfigToModal();
                configAttachModal.style.display = 'flex';
            });

            // 保存配置
            saveConfigAttachBtn.addEventListener('click', () => {
                const extText = document.getElementById('allowed-extensions-input').value.trim();
                const folderText = document.getElementById('excluded-folders-input').value.trim();

                if (!extText || !folderText) {
                    alert("请填写完整！");
                    return;
                }

                const extensions = extText.split('\n')
                    .map(ext => ext.trim().toLowerCase())
                    .filter(ext => ext);

                const folders = folderText.split('\n')
                    .map(f => f.trim())
                    .filter(f => f);

                // 验证格式（简单检查是否以点开头）
                const invalidExt = extensions.find(ext => !ext.startsWith('.'));
                if (invalidExt) {
                    alert(`无效的扩展名格式：${invalidExt}，应以 "." 开头。`);
                    return;
                }

                const config = { allowedExtensions: extensions, excludeFolders: folders };
                localStorage.setItem('attachConfig', JSON.stringify(config));
                alert('附件配置已保存！');
                configAttachModal.style.display = 'none';
            });

            // 取消关闭
            cancelConfigAttachBtn.addEventListener('click', () => {
                configAttachModal.style.display = 'none';
            });


            importFileInput.addEventListener('change', function (event) {
                const files = event.target.files;
                if (!files || files.length === 0) {
                    return;
                }

                const config = getAttachConfig(); // 替代原来 hardcode 的数组
                const allowedExtensions = config.allowedExtensions;

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();

                    if (!allowedExtensions.includes(ext)) {
                        alert(`已跳过不支持的文件类型：${file.name}`);
                        continue;
                    }

                    const reader = new FileReader();
                    reader.onload = function (e) {
                        fileList.push({
                            title: file.name,
                            content: e.target.result
                        });
                        updateFileList();
                    };
                    reader.onerror = () => {
                        console.warn(`无法读取文件：${file.name}`);
                    };
                    reader.readAsText(file);
                }
            });

            importDirInput.addEventListener('change', function (event) {
                const files = event.target.files;
                if (!files || files.length === 0) {
                    return;
                }

                const config = getAttachConfig();
                const excludeFolders = config.excludeFolders;
                const allowedExtensions = config.allowedExtensions;

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const relativePath = file.webkitRelativePath; // 包含路径信息

                    // 检查路径是否包含任何被排除的文件夹
                    const shouldExcludeFolder = excludeFolders.some(folder =>
                        relativePath.includes('/' + folder + '/') || relativePath.startsWith(folder + '/')
                    );
                    if (shouldExcludeFolder) {
                        continue;
                    }

                    // 获取文件扩展名并检查是否允许
                    const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
                    if (!allowedExtensions.includes(ext)) {
                        continue;
                    }

                    // 仅处理文本文件类型
                    if (!file.type || file.type.startsWith('text/') || file.type === '' || file.type === 'application/json') {
                        const reader = new FileReader();
                        reader.onload = function (e) {
                            fileList.push({
                                title: file.webkitRelativePath, // 显示完整路径更清晰
                                content: e.target.result
                            });
                            updateFileList();
                        };
                        reader.onerror = () => {
                            console.warn(`无法读取文件：${file.webkitRelativePath}`);
                        };
                        reader.readAsText(file);
                    }
                }
            });

            attachBtn.addEventListener('click', () => {
                attachModal.style.display = 'flex';
            });

            saveAttachBtn.addEventListener('click', () => {
                attachContent = "";
                for (let i = 0; i < fileList.length; i++) {
                    attachContent += "\n";
                    attachContent += "文件名：" + fileList[i].title;
                    attachContent += "\n";
                    attachContent += "文件内容：" + fileList[i].content;
                    attachContent += "\n";
                }
                attachModal.style.display = 'none';
            });

            cancelAttachBtn.addEventListener('click', () => {
                attachContent = "";
                attachModal.style.display = 'none';
            });

            const historyBtn = document.getElementById('history-btn');
            const historyModal = document.getElementById('history-modal');
            const changeHistoryBtn = document.getElementById('change-history-btn');
            const cancelHistoryBtn = document.getElementById('cancel-history-btn');
            const historyListElem = document.getElementById('history-list');

            historyBtn.addEventListener('click', () => {
                if (isAnswering) {
                    alert("当前正在回答中！");
                    return;
                }
                const html = document.createElement("div");
                for (let i = 0; i < historyList.length; i++) {
                    const p = document.createElement("p");
                    p.setAttribute("msgId", historyList[i].id);
                    p.textContent = historyList[i].question;
                    html.appendChild(p);
                }
                historyListElem.innerHTML = "";
                historyListElem.appendChild(html);
                const pList = historyListElem.getElementsByTagName("p");
                for (let i = 0; i < pList.length; i++) {
                    pList[i].onclick = function () {
                        for (let j = 0; j < pList.length; j++) {
                            pList[j].className = "";
                        }
                        pList[i].className = "active";
                    }
                }
                historyModal.style.display = 'flex';
            });

            changeHistoryBtn.addEventListener('click', () => {
                historyModal.style.display = 'none';
                const pList = historyListElem.getElementsByTagName("p");
                for (let i = 0; i < pList.length; i++) {
                    if (pList[i].classList.contains("active")) {
                        const msgId = pList[i].getAttribute("msgId");
                        for (let j = 0; j < historyList.length; j++) {
                            if (historyList[j].id === parseInt(msgId)) {
                                codeInput.value = historyList[j].question;
                                replyContent = historyList[j].reply;
                                preview.textContent = "";
                                preview.appendChild(getMarkedDom(historyList[j].reply));
                                preview.scrollTop = preview.scrollHeight;
                                break;
                            }
                        }
                        break;
                    }
                }
            });

            cancelHistoryBtn.addEventListener('click', () => {
                historyModal.style.display = 'none';
            });

            let isAnswering = false;
            let replyContent = "";
            const historyList = [];

            if (localStorage.getItem("historyList")) {
                const historyListTemp = JSON.parse(localStorage.getItem("historyList"));
                for (let i = 0; i < historyListTemp.length; i++) {
                    historyList.push(historyListTemp[i]);
                }
            }

            function callGpt(questionText) {
                isAnswering = true;

                fetch("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", {
                    method: "post",
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": `Bearer ${localStorage.getItem("sk")}`
                    },
                    body: JSON.stringify({
                        model: "qwen-plus",
                        messages: [{
                            role: "assistant",
                            content: questionText,
                        }],
                        stream: true
                    }),
                }).then(response => {
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder('utf-8');
                    let viewText = "";

                    function read() {
                        reader.read().then(({done, value}) => {
                            if (done) {
                                isAnswering = false;
                                replyContent = viewText;
                                historyList.push({
                                    id: Date.now(),
                                    question: questionText,
                                    reply: viewText,
                                });
                                localStorage.setItem("historyList", JSON.stringify(historyList));
                                attachContent = "";
                                alert("回答完成");
                                return;
                            }
                            const text = decoder.decode(value, {stream: true});
                            const chunks = text.replace("data: [DONE]", "").replace("data: ", "").split("data: ");
                            for (let i = 0; i < chunks.length; i++) {
                                try {
                                    const obj = JSON.parse(chunks[i]);
                                    const choices = obj.choices;
                                    const delta = choices[0].delta;
                                    viewText += delta.content;
                                    preview.textContent = "";
                                    preview.appendChild(getMarkedDom(viewText));
                                    preview.scrollTop = preview.scrollHeight;
                                } catch (e) {
                                    console.log(chunks[i])
                                    read();
                                }
                            }

                            read();
                        }).catch(error => {
                            isAnswering = false;
                            console.log(error);
                            alert("工具处理出错：" + error);
                        });
                    }

                    read();
                }).catch(error => {
                    isAnswering = false;
                    console.log(error);
                    alert("工具处理出错：" + error);
                });
            }

            function getMarkedDom(text) {
                // 解析 Markdown 文本为 HTML
                const htmlContent = marked.parse(text);

                // 创建一个临时容器来存放解析后的 HTML
                const tempContainer = document.createElement('div');
                tempContainer.innerHTML = htmlContent;

                // 高亮代码块
                tempContainer.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightBlock(block);

                    // 为每个代码块添加复制按钮
                    const copyButton = document.createElement('button');
                    copyButton.textContent = '复制';
                    copyButton.className = 'copy-button';
                    copyButton.style.position = 'absolute';
                    copyButton.style.right = '10px';
                    copyButton.style.top = '10px';
                    copyButton.style.padding = '5px 10px';
                    copyButton.style.background = '#3498db';
                    copyButton.style.color = 'white';
                    copyButton.style.border = 'none';
                    copyButton.style.borderRadius = '4px';
                    copyButton.style.cursor = 'pointer';
                    copyButton.style.transition = 'background 0.3s';

                    // 复制按钮点击事件
                    copyButton.addEventListener('click', () => {
                        if (isAnswering) {
                            alert("当前正在回答中！");
                            return;
                        }
                        const codeContent = block.textContent;
                        navigator.clipboard.writeText(codeContent).then(() => {
                            copyButton.textContent = '已复制';
                            setTimeout(() => {
                                copyButton.textContent = '复制';
                            }, 3000); // 3秒后恢复
                        }).catch(() => {
                            alert('复制失败，请手动复制！');
                        });
                    });

                    // 将复制按钮添加到代码块的父元素（pre）中
                    const preElement = block.parentElement;
                    preElement.style.position = 'relative'; // 设置相对定位
                    preElement.appendChild(copyButton);

                    if (preElement.getElementsByTagName("code").length > 0) {
                        const classList = preElement.getElementsByTagName("code")[0].classList;
                        if (classList.contains("language-html")) {
                            // 为每个代码块添加预览按钮
                            const previewButton = document.createElement('button');
                            previewButton.textContent = '预览';
                            previewButton.className = 'preview-button';
                            previewButton.style.position = 'absolute';
                            previewButton.style.right = '80px';
                            previewButton.style.top = '10px';
                            previewButton.style.padding = '5px 10px';
                            previewButton.style.background = '#3498db';
                            previewButton.style.color = 'white';
                            previewButton.style.border = 'none';
                            previewButton.style.borderRadius = '4px';
                            previewButton.style.cursor = 'pointer';
                            previewButton.style.transition = 'background 0.3s';

                            // 预览按钮点击事件
                            previewButton.addEventListener('click', () => {
                                if (isAnswering) {
                                    alert("当前正在回答中！");
                                    return;
                                }
                                const codeContent = block.textContent;
                                previewHTML(codeContent);
                            });

                            function previewHTML(htmlString) {
                                // 创建一个 Blob 对象，类型为 'text/html'
                                const blob = new Blob([htmlString], {type: 'text/html'});

                                // 创建一个临时的 URL 指向这个 Blob 对象
                                const url = URL.createObjectURL(blob);

                                // 打开一个新的标签页并加载这个 URL
                                const newWindow = window.open(url, '_blank');

                                // 确保新窗口已成功打开
                                if (newWindow) {
                                    // 新窗口已成功打开，可以进行其他操作
                                    newWindow.focus();
                                } else {
                                    // 如果浏览器阻止了弹出窗口，提示用户手动打开
                                    alert('请允许弹出窗口以预览 HTML。');
                                }

                                // 释放掉这个临时的 URL
                                setTimeout(() => URL.revokeObjectURL(url), 5000); // 5秒后释放URL
                            }

                            // 将预览按钮添加到代码块的父元素（pre）中
                            preElement.appendChild(previewButton);
                        }
                    }
                });

                // 返回 DOM 元素列表
                return tempContainer;
            }

            // 生成 HTML 文件内容
            function generateHTMLFile() {
                const content = document.getElementById('preview').innerHTML;
                const style = `
                    <style>
                        * {
                            box-sizing: border-box;
                        }

                        body {
                            font-family: 'Inter', sans-serif;
                            background: linear-gradient(135deg, #f0f4f8, #d1d9e6);
                            color: #333;
                            line-height: 1.6;
                            height: 100vh;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            padding: 20px;
                            margin: 0;
                        }

                        body::-webkit-scrollbar {
                            width: 0.5rem;
                        }

                        body::-webkit-scrollbar-track {
                            background: #f1f1f1;
                            border-radius: 0.5rem;
                        }

                        body::-webkit-scrollbar-thumb {
                            background: #3498db;
                            border-radius: 0.5rem;
                        }

                        body::-webkit-scrollbar-thumb:hover {
                            background: #2980b9;
                        }

                        #preview {
                            width: 100%;
                            height: 100%;
                            padding: 20px;
                            border: 2px solid #e0e0e0;
                            border-radius: 8px;
                            overflow-y: auto;
                            scroll-behavior: smooth;
                            background-color: #ffffff;
                            color: #333;
                        }

                        #preview::-webkit-scrollbar {
                            width: 0.5rem;
                        }

                        #preview::-webkit-scrollbar-track {
                            background: #f1f1f1;
                            border-radius: 0.5rem;
                        }

                        #preview::-webkit-scrollbar-thumb {
                            background: #3498db;
                            border-radius: 0.5rem;
                        }

                        #preview::-webkit-scrollbar-thumb:hover {
                            background: #2980b9;
                        }

                        #preview * {
                          box-sizing: border-box;
                        }

                        #preview h1, h2, h3 {
                          margin-top: 1.5rem !important;
                          margin-bottom: 1rem !important;
                          color: #2c3e50;
                        }

                        #preview h1 {
                          font-size: 2rem;
                          border-bottom: 2px solid #e0e0e0;
                          padding-bottom: 0.5rem;
                        }

                        #preview h2 {
                          font-size: 1.75rem;
                        }

                        #preview h3 {
                          font-size: 1.5rem;
                        }

                        #preview p {
                          margin-bottom: 1rem;
                          line-height: 1.8;
                        }

                        #preview a {
                          color: #3498db;
                          text-decoration: none;
                          font-weight: 500;
                        }

                        #preview a:hover {
                          text-decoration: underline;
                        }

                        #preview ul, ol {
                          margin-bottom: 1rem;
                          padding-left: 1.5rem;
                        }

                        #preview ul {
                          list-style-type: disc;
                          margin-top: 10px;
                        }

                        #preview ol {
                          list-style-type: decimal;
                          margin-left: 1rem;
                        }

                        #preview li {
                          margin-bottom: 0.5rem;
                        }

                        #preview code {
                          font-family: 'JetBrains Mono', monospace;
                          background-color: #f5f7ff;
                          padding: 2px 6px;
                          border-radius: 4px;
                          color: #2c3e50;
                          font-size: 14px;
                        }

                        #preview pre {
                          background-color: #f5f7ff;
                          padding: 15px;
                          border-radius: 6px;
                          margin: 1rem 0;
                          font-size: 14px;
                          line-height: 1.5;
                          overflow: auto;
                        }

                        #preview pre::-webkit-scrollbar {
                            width: 0.5rem;
                            height: 0.5rem;
                        }

                        #preview pre::-webkit-scrollbar-track {
                            background: #f1f1f1;
                            border-radius: 0.5rem;
                        }

                        #preview pre::-webkit-scrollbar-thumb {
                            background: #3498db;
                            border-radius: 0.5rem;
                        }

                        #preview pre::-webkit-scrollbar-thumb:hover {
                            background: #2980b9;
                        }

                        #preview pre code {
                          background-color: transparent;
                          padding: 0;
                          color: #2c3e50;
                          width: fit-content;
                        }

                        #preview pre code .copy-button {
                            position: absolute;
                            right: 10px;
                            top: 10px;
                            background-color: #3498db;
                            color: white;
                            border: none;
                            padding: 5px 10px;
                            border-radius: 4px;
                            cursor: pointer;
                            font-size: 14px;
                            transition: background-color 0.3s;
                        }

                        #preview pre code .copy-button:hover {
                            background-color: #2980b9;
                        }

                        #preview pre code .preview-button {
                            position: absolute;
                            right: 80px;
                            top: 10px;
                            background-color: #3498db;
                            color: white;
                            border: none;
                            padding: 5px 10px;
                            border-radius: 4px;
                            cursor: pointer;
                            font-size: 14px;
                            transition: background-color 0.3s;
                        }

                        #preview pre code .preview-button:hover {
                            background-color: #2980b9;
                        }

                        #preview blockquote {
                          border-left: 4px solid #3498db;
                          color: #555;
                          margin: 1rem 0;
                          font-style: italic;
                          background-color: #f0f4f8;
                          padding: 10px;
                          border-radius: 4px;
                        }

                        #preview table {
                            border-spacing: 0;
                            border-collapse: collapse;
                        }

                        #preview table tr {
                            border-top: 1px solid #c6cbd1;
                        }

                        #preview table tr td, table tr th {
                            padding: 6px 13px !important;
                            border: 1px solid #dfe2e5;
                        }

                        #preview hr {
                            margin: 20px !important;
                        }
                    </style>
                `;

                const script = getScript();

                return `
                    <!DOCTYPE html>
                    <html lang="zh-CN">
                    <head>
                        <meta charset="UTF-8">
                        <meta name="viewport" content="width=device-width, initial-scale=1.0">
                        <title>导出回答</title>
                        <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Inter:wght@400;500;700&display=swap" rel="stylesheet">
                        <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css" rel="stylesheet">
                        ${style}
                    </head>
                    <body>
                        <div id="preview">
                            ${content}
                        </div>
                        ${script}
                    </body>
                    </html>
                `;
            }

            function getScript() {
                return `
                    <script>
                        const copyButtons = document.getElementsByClassName("copy-button");
                        for(let i = 0; i < copyButtons.length; i++) {
                            copyButtons[i].addEventListener('click', () => {
                                if (copyButtons[i].parentElement.getElementsByTagName("code")) {
                                    const codeContent = copyButtons[i].parentElement.getElementsByTagName("code")[0].textContent;
                                    navigator.clipboard.writeText(codeContent).then(() => {
                                        copyButtons[i].textContent = '已复制';
                                        setTimeout(() => {
                                            copyButtons[i].textContent = '复制';
                                        }, 3000);
                                    }).catch(() => {
                                        alert('复制失败，请手动复制！');
                                    });
                                }
                            });
                        }

                        const previewButtons = document.getElementsByClassName("preview-button");
                        for(let i = 0; i < previewButtons.length; i++) {
                            previewButtons[i].addEventListener('click', () => {
                                if (previewButtons[i].parentElement.getElementsByTagName("code")) {
                                    const codeContent = previewButtons[i].parentElement.getElementsByTagName("code")[0].textContent;
                                    previewHTML(codeContent);
                                }
                            });
                        }

                        function previewHTML(htmlString) {
                            // 创建一个 Blob 对象，类型为 'text/html'
                            const blob = new Blob([htmlString], { type: 'text/html' });

                            // 创建一个临时的 URL 指向这个 Blob 对象
                            const url = URL.createObjectURL(blob);

                            // 打开一个新的标签页并加载这个 URL
                            const newWindow = window.open(url, '_blank');

                            // 确保新窗口已成功打开
                            if (newWindow) {
                                // 新窗口已成功打开，可以进行其他操作
                                newWindow.focus();
                            } else {
                                // 如果浏览器阻止了弹出窗口，提示用户手动打开
                                alert('请允许弹出窗口以预览 HTML。');
                            }

                            // 释放掉这个临时的 URL
                            setTimeout(() => URL.revokeObjectURL(url), 5000); // 5秒后释放URL
                        }
                    <\/script>
                `;
            }
        </script>
    </body>

</html>
